/**
 * Created by zaranengap on 2018/02/08
 */
import React from "react";
import { connect } from "react-redux";
import menuRoute from "routes/menuRoute";
import "styles/expense-report/base-expense-report-detail.scss";
import moment from "moment";
import ExpenseTypePie from "containers/expense-report/expense-type-pie";
import {
  Tabs,
  Icon,
  Row,
  Col,
  Button,
  Affix,
  message,
  Modal,
  Popconfirm,
  Radio,
  Spin,
  Tooltip,
  Table,
} from "antd";
const RadioGroup = Radio.Group;
const confirm = Modal.confirm;
const TabPane = Tabs.TabPane;
import ApproveExpenseReportDetail from "containers/approve/expense-report/approve-expense-report-detail";
import AuditApplicationDetail from "containers/financial-management/finance-audit/audit-application-detail";
import expenseReportService from "containers/expense-report/expense-report.service";
import expenseService from "containers/my-account/expense.service";
import baseService from "share/base.service";
import NewExpense from "containers/my-account/new-expense";
import PayInfo from "containers/expense-report/template/pay-info";
import SlideFrame from "components/slide-frame";
import {
  messages,
  invoiceAmountChange,
  removeArryItem,
  deepFullCopy,
  getQueryUrlParam,
  addCalculate,
  currencyPrecisionCal,
  queryCurrencyPrecision,
  formatNumber
} from "share/common";
import loadingImg from "images/expense-report/loading.png";
import auditingImg from "images/expense-report/auditing.png";
import { ExternalExpenseImport } from "components/index";
import YingfuSelectApprove from "containers/expense-report/template/yingfu-select-approve";
import { notification } from "antd/lib/index";
import confirmPaymentService from "../financial-management/confirm-payment/confirm-payment.service";
import ApproveHistory from "components/template/approve-history";
import errorMessage from "share/errorMessage";
import { setDocumentaryCompany, setLoginCompany } from "actions/login";
import configureStore from "stores";
import Selector from "components/selector";
import Condition from "components/condition";
const { If, Else } = Condition;
import ExpenseDetailHeader from "containers/expense-report/components/expense-detail-header";
import ExpenseCalendarTable from "containers/expense-report/components/expense-calendar-table";
import ExpenseCheckResult from "containers/expense-report/components/expense-check-result";
import SubsidySlideFrame from "containers/expense-report/components/subsidy-slide-frame";
import ExpenseAccountTable from "containers/expense-report/components/expense-account-table";
import ButtonPrintCertificate from "containers/expense-report/components/button-print-certificate";
import ButtonBatchApportion from "containers/expense-report/components/button-batch-apportion";
import ButtonsBarBottom from "containers/expense-report/components/buttons-bar-bottom";
import ExpenseReportFields from "containers/expense-report/components/expense-report-fields";
import ExpenseAssociatedBag from "containers/expense-report/components/expense-associated-bag";
import BudgetExplain from "components/template/budget-explain/budget-explain";
import ConcurrentMark from "containers/expense-report/template/concurrent-mark";
import AuditApplicationInvoices from "containers/financial-management/finance-audit/audit-application-invoices";
import CertificatePreview from "containers/financial-management/finance-audit/certificate-preview";
import expenseReportFunction from "containers/expense-report/expense-report.function";
const {
  getReportStatus,
  filterExpenseList,
  isApproveButtonsShow,
  handleSubmitError,
  renderModalInfo,
} = expenseReportFunction;
import expenseReportData from "containers/expense-report/expense-report.data";
const { auditTabs } = expenseReportData;
import ButtonExportAccount from "containers/expense-report/components/button-export-account";
import leftArrow from "../expense/svg-component/left-arrow";
import ExpenseDetailAlert from "containers/expense-report/components/expense-detail-alert";
import UnifiedTable from "components/template/widget/unified-table/UnifiedTable";
import financeAuditService from "containers/financial-management/new-finance-audit/finance-audit.service";
import ExpenseDetailStep from "containers/expense-report/components/expense-detail-step";

//思路：对json数据解析，应该是两个数组，外面的数组长度进行一次遍历，获得最终的合计，对第二层的数组进行遍历，获得中间的小计
const overAppcolumns = [
  {
    title: messages("common.expense.type") /*费用类型*/,
    dataIndex: "invoiceType",
    width: 48,
  },
  {
    title: messages("expense-parent-report.key360") /*关联申请单单号*/,
    dataIndex: "businessCode",
    width: 100,
  },
  {
    title: messages("expense-parent-report.key361") /*关联申请单金额*/,
    dataIndex: "invoicesAmt",
    align: 'right',
    width: 48,
    render: (text, record, index) => {
      return (
        <span>{formatNumber(text)}</span>
      )
    }
  },
  {
    title: messages("expense-parent-report.key323") /*累计已报销金额*/,
    dataIndex: "remainAmt",
    align: 'right',
    width: 60,
    render: (text, record, index) => formatNumber(text)
  },
  {
    title: messages("expense-parent-report.key363") /*本次报销金额*/,
    dataIndex: "curInvoicesAmt",
    align: 'right',
    width: 48,
    render: (text, record, index) => formatNumber(text)
  },
  {
    title: messages("expense-parent-report.key364") /*超申请金额*/,
    dataIndex: "overBillAmt",
    align: 'right',
    width: 48,
    render: (text, record, index) => formatNumber(text)
  },
];

const overQuotacolumns = [
  {
    title: messages("pay.refund.documentNumber") /*单据编号*/,
    dataIndex: "businessCode",
    width:200
  },
  {
    title: messages("finance-7.key103") /*费用发生日期*/,
    dataIndex: "date",
    width: 150,
    render: (text, record, index) => moment(text).format('YYYY-MM-DD')
  },
  {
    title: messages("data-center.key3") /*描述*/,
    width:100,
    dataIndex: "description",
  },
  {
    title: messages("common.currency") /*币种*/,
    width: 100,
    dataIndex: "currency",
  },
  {
    title: messages("common.amount") /*金额*/,
    dataIndex: "amt",
    width: 100,
    render: (text, record, index) => formatNumber(Number(text).toFixed(2))
  },
  {
    title: messages("common.applicant") /*申请人*/,
    width: 100,
    dataIndex: "name",
  },
];

class ExpenseReportDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // https://pmo.mcd.com.cn/jira/browse/TES-786
      reportInvoiceApprovalReqDTOList: [],
      accountListLoading: false,
      loading: true,
      showApproveBottom: false, //审批中是否展示底部按钮
      tabValue: "requestInfo",
      auditTabsValue: "waitAudit",
      applicant: {},
      form: {},
      info: {}, //报销单详情
      isOverBill: false,
      overAppData: [], //超申请信息
      haveAutoAudit: false, //是否有自动审核费用
      approvalHistory: [],
      showExpenseReportInvoices: [],
      expenseReportInvoices: [],
      showNewExpense: false,
      nowEditExpense: null,
      expenseSource: "expenseType",
      checkingText: "",
      showChecking: false,
      submitting: false,
      checkResult: [],
      showCheckResult: false,
      printLoading: false,
      pay: false, //付款页面
      approve: false, //审批页面
      audit: false, //审核页面
      view: false, //查看页面
      loanRefund: false, //借还款页面
      readOnly: false, //只可读
      businessCardEnabled: false,
      invoiceEnabled: false,
      ocrEnabled: false,
      expenseRowSelection: {
        type: props.profile["app.approval.reject.batch.disabled"]
          ? "radio"
          : "checkbox",
        selectedRowKeys: [],
        onChange: this.onSelectExpense,
        getCheckboxProps: (record) => ({
          disabled: record.status === 1002,
        }),
      },
      directSubmitting: false,
      showExternalExpenseImportModal: false,
      showYingfuSelectApproveModal: false,
      travelSubsidy: null,
      travelSubsidyType: null,
      travelSubsidyUser: "all",
      costCenterItemsApportion: [], //参与分摊的成本中心
      auditCapability: false,
      confirmLoading: false,
      subsidyFrame: false, //补贴侧边拦
      isWithSubsidies: false, //是否需要补贴计算
      isWithTime: false, //补贴计算是否需要时分
      selectInvoiceOIDs: [], //付款行选择费用
      expenseRowIsEdit: false, //费用行是否被修改了，用于多付款行的刷新
      modalVisible: false,
      owner: {}, //费用归属人信息
      ownerOID: "", //费用归属人OID
      lineIds: [], //付款行id数组
      receiptOperateScene: 1, //发票操作场景：1.发票创建费用；2.费用新增发票；3.费用编辑发票
      isCopyInvoice: false,
      debounceSlideFrame: false, //侧滑框防抖，解决快速关闭侧滑框的情况
      isCalendarMode: false,
      filterCondition: {
        owner: [],
        ownerOID: [],
        expenseType: [],
        expenseTypeOID: [],
        date: [],
      },
      filterDataSum: 0,
      invoiceGroups: [], //费用列表分类
      approvalChains: [], //审批链
      budgetExplainNumber: 0, //预算执行情况列表数量
      expenseTypePieChosenIndex: "all", //费用类别选中的index
      batchApportion: false, //开启批量分摊
      isAuditInApproveStatus: false, //是否是处于审核状态下status为1002的单据
      jobInfo: {}, //岗位信息
      showExpensePrew: false,
      showWriteOffPrew: false,
      failedInvoices: [], //未查验或查验失败的发票
      showAssociatedBag: false,
      associatedData: {},
      hasPayInfo: [1],
      /**
       * 公共列表
       * @type {{fieldName:string; formField: string; value: string}[]}
       */
      unifiedTableList: [],
      writeOffLoanList: [],
      overQuotaList: [],
      overQuotaVisible: false,
      isAddMailFreeLabel: undefined
    };
  }

  componentDidMount() {
    this.setState(
      {
        approve:
          this.props.location.pathname.indexOf(
            "approve-expense-report-detail"
          ) > -1,
        audit: this.props.location.pathname.indexOf("finance-audit") > -1,
        view:
          this.props.location.pathname.indexOf("finance-view") > -1 ||
          getQueryUrlParam("readOnly") === "true",
        pay: this.props.location.pathname.indexOf("confirm-payment") > -1,
        loanRefund:
          this.props.location.pathname.indexOf("loan-and-refund") > -1,
      },
      () => {
        this.getInfo(false);
        this.getExpenseList();
        this.isOverBill();
      }
    );
  }

  //根据费用oid判断是否超申请
  isOverBill = (showCheckResult) => {
    let oid = this.props.params.expenseReportOID;
    let overAppData = null;
    let tempData = [];
    expenseReportService.isOverBill(oid).then((res) => {
      if (res.data && res.data.length > 0) {
        //超申请
        this.setState({
          isOverBill: true,
        });
        overAppData = res.data;
        overAppData.map((item) => {
          let temp = [];
          if (item.overBillDataList.length > 0) {
            item.overBillDataList.map((data) => {
              temp.push({
                invoiceType: data.expenseTypeName,
                businessCode: data.businessCode,
                invoicesAmt: Number(data.applicationInvoiceAmt).toFixed(2),
                remainAmt: Number(data.remainAmt).toFixed(2),
                curInvoicesAmt: Number(data.invoiceAmt).toFixed(2),
                overBillAmt: Number(data.overBillAmt).toFixed(2),
              });
            });
            temp.push({
              invoiceType: "",
              businessCode: messages("expense-over-bill.key003" /*小计*/),
              invoicesAmt: Number(item.applicationInvoiceAmt).toFixed(2),
              remainAmt: Number(item.remainAmt).toFixed(2),
              curInvoicesAmt: Number(item.invoiceAmt).toFixed(2),
              overBillAmt: Number(item.overBillAmt).toFixed(2),
            });
          }
          temp.map((item) => {
            tempData.push(item);
          });
        });
      } else {
        this.setState({
          isOverBill: false,
        });
      }
      tempData.push({
        invoiceType: "",
        businessCode: messages("expense-over-bill.key004" /*合计*/),
        invoicesAmt: null,
        remainAmt: null,
        curInvoicesAmt: null,
        overBillAmt: null,
      });
      let totalInvoicesAmt = 0;
      let totalRemainAmt = 0;
      let totalCurInvoicesAmt = 0;
      let totalOverBillAmt = 0;
      tempData.forEach(
        ({
          businessCode,
          invoicesAmt,
          remainAmt,
          curInvoicesAmt,
          overBillAmt,
        }) => {
          if (businessCode == messages("expense-over-bill.key003" /*小计*/)) {
            totalInvoicesAmt += Number(invoicesAmt);
            totalRemainAmt += Number(remainAmt);
            totalCurInvoicesAmt += Number(curInvoicesAmt);
            totalOverBillAmt += Number(overBillAmt);
          }
        }
      );
      tempData[tempData.length - 1].invoicesAmt = Number(totalInvoicesAmt).toFixed(2);
      tempData[tempData.length - 1].remainAmt = Number(totalRemainAmt).toFixed(2);
      tempData[tempData.length - 1].curInvoicesAmt = Number(totalCurInvoicesAmt).toFixed(2);
      tempData[tempData.length - 1].overBillAmt = Number(totalOverBillAmt).toFixed(2);
      this.setState({
        overAppData: tempData,
      });
    });
    if (showCheckResult) {
      this.setState({ showCheckResult: true })
    }
  };

  /**
   * 得到页面信息
   * @param baseOnly 是否只需要报销单详情
   */
  getInfo = (baseOnly) => {
    const { expenseReportOID, tab } = this.props.params;
    const { profile, loginUser } = this.props;
    let {
      isWithSubsidies,
      isWithTime,
      expenseRowSelection,
      approve,
      audit,
      view,
      pay,
      loanRefund,
    } = this.state;
    this.setState({ loading: true });
    expenseReportService
      .getExpenseReportDetail(expenseReportOID)
      .then((response) => {
        let expenseDetail = response.data.rows || {};
        isWithSubsidies = expenseDetail.withSubsidies;
        isWithTime = expenseDetail.withTime;
        this.setState({ isWithSubsidies, isWithTime });
        if (profile["web.invoice.keep.consistent.with.expense"]) {
          expenseDetail.currencySame = true;
        }
        let costCenterItemsApportion = [];
        //查询是否多币种、初始化成本中心项
        expenseDetail.custFormValues.map((field) => {
          if (field.messageKey === "select_cost_center") {
            if (JSON.parse(field.fieldConstraint || "{}").isApportionItem) {
              //参与分摊
              costCenterItemsApportion.push({
                fieldName: field.fieldName,
                costCenterOID: JSON.parse(field.dataSource || "{}")
                  .costCenterOID,
                costCenterItemName: field.showValue,
                name: field.showValue,
                costCenterItemOID: field.value,
                required: field.required,
              });
            }
          }
          if (field.messageKey === "select_department") {
            if (JSON.parse(field.fieldConstraint || "{}").isApportionItem) {
              //参与分摊
              costCenterItemsApportion.push({
                fieldName: field.fieldName,
                costCenterOID: "00000000-0000-0000-0000-000000000000",
                costCenterItemName: field.showValue,
                name: field.showValue,
                costCenterItemOID: field.value,
                required: field.required,
              });
            }
          }
        });
        let expenseReportStatus = getReportStatus(expenseDetail);
        let readOnly =
          expenseReportStatus.operate !== "edit" ||
          approve ||
          audit ||
          view ||
          pay ||
          loanRefund;
        this.setState(
          {
            readOnly,
            costCenterItemsApportion,
            loading: !baseOnly,
            info: expenseDetail,
            selectInvoiceOIDs: [],
            expenseRowIsEdit: true,
          },
          () => {
            this.getCheckInvoiceBtnEnable();
            this.getHistory();
            this.getBudgetExplainNumber();
            !baseOnly && this.getThirdInterface();
            audit &&
              tab === "prending_audit" &&
              this.getCertificatePreviewTab();
            //代提逻辑
            if (expenseReportStatus.operate === "edit") {
              if (loginUser.userOID !== expenseDetail.applicantOID) {
                baseService.changeLoginInfo(expenseDetail.applicantOID);
              }
            }
            if (loginUser.userOID !== expenseDetail.applicantOID) {
              baseService
                .getCompanyByUserOID(expenseDetail.applicantOID)
                .then((res) => {
                  configureStore.store.dispatch(
                    setDocumentaryCompany(res.data)
                  );
                })
                .catch((e) => {
                  configureStore.store.dispatch(setDocumentaryCompany({}));
                });
            } else {
              configureStore.store.dispatch(setDocumentaryCompany({}));
            }

            if (!readOnly) {
              expenseRowSelection.type = "checkbox";
            } else {
              expenseRowSelection = {
                type: profile["app.approval.reject.batch.disabled"]
                  ? "radio"
                  : "checkbox",
                selectedRowKeys: [],
                onChange: this.onSelectExpense,
                getCheckboxProps: (record) => {
                  return {
                    disabled:
                      record.status === 1002 ||
                      record.expenseTypeSubsidyType === 1,
                  };
                },
              };
            }
            this.setState({ expenseRowSelection });
          }
        );
      });
  };

  //获取凭证预览凭证类型tab
  getCertificatePreviewTab = () => {
    const { info } = this.state;
    //查询是否启用核算平台，若未启用则不展示凭证预览
    expenseService.getAccountFlag().then((res) => {
      if (!!res.data) {
        expenseService
          .getCertificatePreviewTab(info.setOfBooksId)
          .then((res) => {
            let showExpensePrew = false;
            let showWriteOffPrew = false;
            res.data &&
              res.data.map((i) => {
                i.templateCode === "GL_EXPENSE" &&
                  i.isEnable === true &&
                  (showExpensePrew = true);
                i.templateCode === "GL_WRITE_OFF" &&
                  i.isEnable === true &&
                  (showWriteOffPrew = true);
              });
            this.setState({ showExpensePrew, showWriteOffPrew });
          });
      }
    });
  };

  /**
   * 公共列表配置以后审核页面要显示明细
   * @see https://pmo.mcd.com.cn/jira/browse/TES-805
   * #746里有特殊处理逻辑，这个逻辑需要保留。保留后的逻辑如下：
   * 如果是商务应酬申请单（SQ001），那么先调用
   * `/api/application/getIsHideParticipantsList?applicationOID=${OID}`
   * 接口判断是会否需要隐藏参与人清单。如果隐藏，
   * 那么这个申请单下的所有公共列表均不展示；如果展示，则正常走#805的逻辑。
   */
  updateUnifiedTableList = () => {
    const { info, form: formInfo } = this.state;
    const fieldMap = {};
    formInfo.customFormFields && formInfo.customFormFields.forEach((field) => {
      if (field.messageKey === "public.assembly") {
        if (!fieldMap[field.fieldOID]) {
          fieldMap[field.fieldOID] = {
            fieldOID: field.fieldOID,
          };
        }
        fieldMap[field.fieldOID].fieldName = field.fieldName;
        fieldMap[field.fieldOID].formField = field.formField;
      }
    });
    info.custFormValues.forEach((item) => {
      if (item.messageKey === "public.assembly") {
        if (!fieldMap[item.fieldOID]) {
          fieldMap[item.fieldOID] = {
            fieldOID: item.fieldOID,
          };
        }
        fieldMap[item.fieldOID].value = item.value;
      }
    });

    const unifiedTableList = Object.values(fieldMap);

    this.setState({
      unifiedTableList,
    });
  };

  //是否显示【发票查验】按钮
  getCheckInvoiceBtnEnable = () => {
    const { params, loginUser } = this.props;
    let applicantOID = "";
    if (
      this.state.info.applicantOID &&
      this.state.info.applicantOID.length > 0
    ) {
      applicantOID = this.state.info.applicantOID;
    } else {
      applicantOID = loginUser.userOID;
    }
    Promise.all([
      expenseReportService.checkInvoice(params.expenseReportOID),
      expenseService.getTitleList(applicantOID),
    ]).then((res) => {
      this.setState({
        failedInvoices: res[0].data || [],
        invoiceEnabled: res[1].data.showCheckInvoiceFlag,
        ocrEnabled: res[1].data.showOCRFlag,
      });
    });
  };

  /**
   * 获取报销单费用列表参数，如果在财务审核模式需要带financeQuery参数以获取发票图片
   */
  getExpenseListParams = () => {
    const { approve, audit, view, pay, auditCapability } = this.state;
    const { expenseReportOID } = this.props.params;
    const backUrlKey = getQueryUrlParam('backUrlKey');
    // console.log('backUrlKey', backUrlKey)
    let params = { expenseReportOID };
    (approve || audit || view || pay || auditCapability) &&
      (params.financeQuery = "Y");
    if (backUrlKey === 'done-approved') {
      params.handled = true;
    }
    if (this.props.params.tab === "prending_audit" || this.props.params.tab === "finance-view-expense" || this.props.params.tab === "audit_pass") {
      params.finance = true;
    }
    return params;
  };

  //获取预算执行结果数量
  getBudgetExplainNumber = () => {
    const { info } = this.state;
    let params = {
      documentType: "EXP_REPORT",
      documentId: info.id,
    };
    expenseReportService.getBudgetExplainCount(params).then((res) => {
      this.setState({ budgetExplainNumber: res.data });
    });
  };

  //获取费用列表
  getExpenseList = () => {
    this.setState({ accountListLoading: true });
    expenseReportService
      .getExpenseAccountInfo(this.getExpenseListParams())
      .then((res) => {
        let haveAutoAudit = false;
        let invoiceGroups =
          res.data && res.data.rows ? res.data.rows.invoiceGroups || [] : [];
        let expenseReportInvoices =
          res.data && res.data.rows
            ? res.data.rows.expenseReportInvoices || []
            : [];
        expenseReportInvoices.map((item) => {
          item.invoiceView &&
            item.invoiceView.autoAudit &&
            (haveAutoAudit = true);
        });
        let showExpenseReportInvoices = filterExpenseList(
          expenseReportInvoices
        );
        this.setState({
          invoiceGroups,
          haveAutoAudit,
          expenseReportInvoices,
          accountListLoading: false,
          showExpenseReportInvoices: this.filterAutoAuditInvoice(
            showExpenseReportInvoices
          ),
          showExpenseReportInvoicesIncludeAllTab: expenseReportInvoices,
        });
      });
  };

  //获取审批历史
  getHistory = () => {
    const { user, location, loginUser } = this.props;
    const { expenseReportOID } = this.props.params;
    const { approve, audit, view, pay, info } = this.state;
    expenseReportService.getExpenseHistoryInfo(expenseReportOID).then((res) => {
      let approvalHistory = (res.data.rows || {}).approvalHistoryDTOs || [];
      let approvalChains = (res.data.rows || {}).approvalChains || [];
      // 单据审核的审批历史节点变动, 导致approvalChains不需要再额外判断
      // let currentApproval = approvalChains
      //   ? approvalChains.filter((i) => i.approverOID === loginUser.userOID)
      //   : [];
      let currentApproval = approvalChains
      this.setState({
        isAuditInApproveStatus:
          currentApproval.length &&
          currentApproval[0].nodeType === 1012 &&
          currentApproval[0].currentFlag,
      });
      if (
        location.pathname.indexOf("approve-expense-report-detail") > -1 &&
        approvalChains &&
        approvalChains.length
      ) {
        //节点类型nodeType 1001审批节点（默认）   1012审核节点
        //invoiceAllowUpdateType 能否修改核定金额
        let auditCapability =
          approvalChains[0].invoiceAllowUpdateType === 1 &&
          ((approve && approvalChains[0].nodeType === 1001) ||
            (audit && approvalChains[0].nodeType === 1012));
        this.setState(
          {
            auditCapability,
            showApproveBottom: isApproveButtonsShow(
              approvalChains,
              user.userOID,
              info.status
            ),
          },
          () => {
            //需要的参数有变刷新费用列表
            if (!approve && !audit && !view && !pay && auditCapability)
              this.getExpenseList();
          }
        );
      }
      this.setState({
        approvalHistory,
        approvalChains,
      });
    });
  };

  getThirdInterface = () => {
    const { info, readOnly } = this.state;
    const { expenseReportOID, applicantOID, applicantJobId } = info;
    Promise.all([
      expenseReportService.getFormInfo(expenseReportOID), //表单详情
      baseService.getUserByOID(applicantOID), //申请人详情
      applicantJobId && expenseReportService.getJobInfo(applicantJobId), //岗位信息
    ])
      .then((res) => {
        this.setState(
          {
            loading: false,
            form: res[0].data.rows || {},
            applicant: res[1].data,
            jobInfo: res[2] ? res[2].data || {} : {},
          },
          () => {
            this.updateUnifiedTableList();
          }
        );
      })
      .catch(() => {
        this.setState({ loading: false });
      });
    this.getTravelSubsidy(); //获得差补统计
    //单据只读时，以下按钮都不会显示，故不需要请求以下接口
    if (!readOnly) {
      //是否显示【导入商务卡费用】按钮
      Promise.all([
        /**
         * baseService.getBusinessCardConsumptionList这个接口的page size传0，0时
         * 意味着不是真的想获取公务卡数据，只是想判断这个用户是否有公务卡消费记录
         * 因为获取公务卡消费记录的时候会剔除掉已关联的公务卡消费记录
         * 如果用户的所有公务卡消费记录都被关联了，就查不出来数据了，所以增加了这一条传参约定
         */
        baseService.getBusinessCardConsumptionList(
          "CMBC",
          false,
          applicantOID,
          0,
          0
        ), //是否有商务卡消费记录
        expenseService.getBusinessCardStatus(applicantOID), //商务卡权限
      ]).then((res) => {
        this.setState({
          businessCardEnabled:
            res[1].data.rows &&
            res[0].data.success &&
            res[0].data.rows.length > 0,
        });
      });
      this.getBatchApportionEnabled(); //是否显示【批量分摊】按钮
    }
  };

  //获取是否开启了批量分摊
  getBatchApportionEnabled = () => {
    const { info } = this.state;
    info.expenseReportOID &&
      expenseReportService
        .getBatchApportionEnable(info.expenseReportOID)
        .then((res) => {
          this.setState({ batchApportion: res.data && res.data.enabled });
        });
  };

  //获得差补统计
  getTravelSubsidy = () => {
    const { expenseReportOID } = this.props.params;
    const { info } = this.state;
    expenseReportService
      .getTravelSubsidy(expenseReportOID, info.applicantOID, 1)
      .then((res) => {
        this.setState({ travelSubsidy: res.data.rows });
      });
  };

  // handleAuditChange https://pmo.mcd.com.cn/jira/browse/TES-786
  handleAuditChange = (changelist) => {
    const { expenseReportOID } = this.props.params;

    let reportInvoiceApprovalReqDTOList =
      this.state.reportInvoiceApprovalReqDTOList || [].slice();
    // console.log("changelist", reportInvoiceApprovalReqDTOList)
    changelist.forEach((change) => {
      const { value, key, record } = change;
      console.log(value, key, record);

      let found = false;

      reportInvoiceApprovalReqDTOList = reportInvoiceApprovalReqDTOList.map(
        (item) => {
          if (item.invoiceOID === record.invoiceOID) {
            found = true;
            return {
              ...item,
              [key]: value,
            };
          }
          return item;
        }
      );
      // console.log("reportInvoiceApprovalReqDTOList", reportInvoiceApprovalReqDTOList)
      if (!found) {
        const {
          expenseReportInvoiceOID,
          invoiceOID,
          expenseTypeName,
          amount,
          createdDate,
          approvalStatus
        } = record;
        const req = {
          // 默认值1001
          approvalStatus: approvalStatus || 1001,
          expenseReportOID,
          // expenseReportInvoiceOID,
          invoiceOID,
          expenseTypeName,
          amount,
          createdDate,
          [key]: value,
        };
        reportInvoiceApprovalReqDTOList.push(req);
      }
    });
    // console.log('reportInvoiceApprovalReqDTOList', reportInvoiceApprovalReqDTOList)
    this.setState({ reportInvoiceApprovalReqDTOList });
  };

  //提交
  handleSubmit = () => {
    let { info, expenseReportInvoices, approvalHistory } = this.state;
    //初始化流程状态
    this.setState({ isRunYingFuApproveFlow: false }, () => {
      if (expenseReportInvoices.length === 0) {
        message.error(messages("expense-parent-report.key9" /*请先添加费用*/));
      } else {
        info.expenseReportInvoices = expenseReportInvoices;
        this.setState({ submitting: true, info });
        let addSign = [];
        if (info.countersignApproverNames) {
          info.countersignApproverNames.map((item) => {
            addSign.push(item.fullName);
          });
        }
        let repeat = [];
        approvalHistory.map((item) => {
          item.operation === 2001 &&
            item.operator &&
            ~addSign.indexOf(item.operator.fullName) &&
            repeat.push(item.operator.fullName);
        });
        let names = [...new Set(repeat)];
        if (names.length) {
          Modal.confirm({
            title: `${names.join("、")} ${messages(
              "expense-parent-report.key10" /*已经审批通过，是否继续*/
            )}？`,
            onOk: () => this.checkBagAssociated(),
            onCancel: () => {
              this.setState({ submitting: false });
            },
          });
        } else {
          this.checkBagAssociated();
        }
      }
    });
  };

  //报销单关联发票袋查验
  checkBagAssociated = () => {
    const { expenseReportOID } = this.props.params;
    expenseReportService.addMailFreeLabel(expenseReportOID).then(result => {
      console.log("result", result)
      // if (result.data) {
      //   expenseReportService.checkBagAssociated(expenseReportOID).then((res) => {
      //     if (res.data.success) {
      //       this.handleCheckTravelStandard();
      //     } else {
      //       this.setState({ showAssociatedBag: true, associatedData: res.data });
      //     }
      //   });
      // }

      // 11.9 免邮寄修改
      expenseReportService.checkBagAssociated(expenseReportOID).then((res) => {
        if (res.data.success) {
          this.setState({
            isAddMailFreeLabel: result.data
          }, () => {
            this.handleCheckTravelStandard();
          })
        } else {
          this.setState({ showAssociatedBag: true, associatedData: res.data, isAddMailFreeLabel: result.data });
        }
      });
    });
  };

  //检查差标
  handleCheckTravelStandard = () => {
    let { info, expenseReportInvoices } = this.state;
    this.setState({
      showChecking: true,
      checkingText: messages(
        "expense-parent-report.key11" /*正在进行提交校验...*/
      ),
    });
    //差标检查
    expenseReportService
      .checkStandard(info)
      .then((res) => {
        this.setState({ showChecking: false, checkingText: "" }, () => {
          let standardResult = res.data;
          if (standardResult.length === 0) {
            this.checkBudget();
          } else {
            let allOk = true;
            let rejectNum = 0;
            let warningNum = 0;
            standardResult.map((result) => {
              allOk = allOk && result.actionType === "OK";
              if (result.actionType === "REJECT") rejectNum++;
              if (result.actionType === "WARNING") warningNum++;
              expenseReportInvoices.map((invoice) => {
                if (invoice.invoiceOID === result.invoiceOID) {
                  invoice.warningFlag = false;
                  invoice.rejectFlag = true;
                  invoice.rejectMesage = result.message;
                  result.actionType !== "OK" &&
                    ((invoice.checkResultStatus = result.actionType),
                    (invoice.checkResultMessage = result.message));
                }
              });
            });
            if (allOk) {
              this.checkBudget();
            } else {
              this.setState({ expenseReportInvoices });
              if (rejectNum > 0) {
                this.setState({ submitting: false });
                Modal.error({
                  title: messages("common.info" /*提示*/),
                  content: messages(
                    "expense-parent-report.key264"
                  ) /*校验失败，请检查！*/,
                  onOk: () => {
                    this.setState({ submitting: false });
                    this.getInfo();
                    this.getExpenseList();
                  },
                });
              } else {
                Modal.confirm({
                  title: messages("common.info" /*提示*/),
                  content: messages(
                    "expense-parent-report.key265"
                  ) /*校验警告，确认提交？*/,
                  onOk: () => this.checkBudget(),
                  okText: messages("expense-parent-report.key12" /*继续提交*/),
                  cancelText: messages(
                    "expense-parent-report.key13" /*返回修改*/
                  ),
                  onCancel: () => {
                    this.setState({ submitting: false });
                    this.getInfo();
                    this.getExpenseList();
                    this.isOverBill();
                  },
                });
              }
            }
          }
        });
      })
      .catch((err) => {
        this.setState({ showChecking: false, submitting: false });
        handleSubmitError(err);
      });
  };

  //预算检查
  checkBudget = () => {
    if (this.checkYingfuApprove()) {
      return;
    }
    let { info } = this.state;
    expenseReportService
      .checkAsync(info.expenseReportOID)
      .then((res) => {
        if (res.data) {
          Modal.confirm({
            content: messages(
              "expense-parent-report.key207"
            ) /*忽略提交过程中的警告信息，直接提交？*/,
            onOk: () => this.handleLastSubmit(true),
            okText: messages("common.yes") /*是*/,
            cancelText: messages("common.no") /*否*/,
            onCancel: () => this.handleLastSubmit(false),
          });
        } else {
          this.handleLastSubmit();
        }
      })
      .catch((e) => {
        this.setState({ submitting: false });
        this.getInfo();
        this.getExpenseList();
        this.isOverBill();
        message.error(e.response.data.message);
      });
  };

  handleLastSubmit = (ignoreWarnCheck = null) => {
    const { info, writeOffLoanList } = this.state;

    this.setState({
      showChecking: true,
      checkingText: messages("common.submitting"),
    }); //正在提交

    const submit = () => {
      if (typeof ignoreWarnCheck === "boolean") {
        info.ignoreWarnCheck = ignoreWarnCheck;
      }
      info.writeOffLoanList = writeOffLoanList;
      info.isAddMailFreeLabel = this.state.isAddMailFreeLabel;
      expenseReportService
        .submitOrCheckBudget(info)
        .then((res) => {
          this.setState({ showChecking: false, checkingText: "" }, () => {
            // true代表可提交， false时提示错误信息
            if (
              !res.data.checkResultList ||
              res.data.checkResultList.length === 0
            ) {
              this.setState({
                submitting: false,
                showChecking: false,
                checkingText: "",
              });
              message.success(messages("common.operate.success")); //操作成功
              this.goBack();
            } else {
              let budgetError = false;
              res.data.checkResultList.map((item) => {
                budgetError = budgetError || item.type === 1;
              });
              this.setState({
                checkResult: res.data.checkResultList,
                showChecking: false,
                checkingText: "",
                // showCheckResult: true,
                submitting: !budgetError,
              }, () => {
                this.isOverBill(true);
              });
            }
          });
        })
        .catch((err) => {
          this.setState({ showChecking: false, submitting: false });
          //https://pmo.mcd.com.cn/jira/browse/TES-1973
          if (err.response.data.errorCode === 'Invoice_Over_Quota_Err') {
            let list = JSON.parse(err.response.data.message);
            console.log('list', list)
            list && list.map(item => {
              item.isShowMore = false;
              let num = 0;
              if (item.subs && item.subs.length > 0) {
                item.subs.map(a => {
                  num += a.amt;
                })
              }
              item.totalTrueAmt = num;
            })
            this.setState({
              overQuotaList: list
            }, () => {
              this.setState({
                overQuotaVisible: true
              })
            })
          } else {
          handleSubmitError(err);
          }
        });
    };

    expenseReportService
      .checkSubmit(info)
      .then((resOfCheck) => {
        if (Array.isArray(resOfCheck.data) && resOfCheck.data.length > 0) {
          Modal.confirm({
            title: "您的提交有下列问题，是否继续提交？",
            content: (
              <div>
                {resOfCheck.data.map((errorItem) => {
                  return <div key={errorItem}>{errorItem}</div>;
                })}
              </div>
            ),
            onOk: () => submit(),
            okText: messages("common.yes") /*是*/,
            cancelText: messages("common.no") /*否*/,
            onCancel: () => {
              this.setState({
                showChecking: false,
              });
            },
          });
        } else {
          submit();
        }
      })
      .catch((error) => {
        this.setState({ showChecking: false, submitting: false });
        errorMessage(error.response);
      });
  };

  //英孚审批流程执行
  checkYingfuApprove = () => {
    let { info, isRunYingFuApproveFlow } = this.state;
    if (isRunYingFuApproveFlow) {
      return false;
    }
    let yingFuApproveFlow = false;
    info.custFormValues &&
      info.custFormValues.map((item) => {
        if (item.messageKey === "ying_fu_select_approver") {
          yingFuApproveFlow = true;
          this.setState({
            showYingfuSelectApproveModal: true,
            isRunYingFuApproveFlow: true,
          });
        }
      });
    return yingFuApproveFlow;
  };

  //提交英孚审批
  submitYingfuApprove = (usersOID) => {
    let { info } = this.state;
    info.custFormValues &&
      info.custFormValues.map((item) => {
        if (item.messageKey === "ying_fu_select_approver") {
          item.value = usersOID;
        }
      });
    this.setState({ info }, () => {
      this.openYingfuSelectApprove(false);
      this.checkBudget();
    });
  };

  //英孚审批控制
  openYingfuSelectApprove = (flag) => {
    this.setState({ showYingfuSelectApproveModal: flag, submitting: false });
  };

  //预算检查时忽略预警直接保存
  confirmSubmit = () => {
    let { info } = this.state;
    info.ignoreBudgetWarningFlag = true;
    this.setState({ directSubmitting: true });
    info.isAddMailFreeLabel = this.state.isAddMailFreeLabel;
    expenseReportService
      .submitOrCheckBudget(info)
      .then((res) => {
        let budgetError = false;
        res.data.checkResultList &&
          res.data.checkResultList.map((item) => {
            budgetError = budgetError || item.type === 1;
          });
        if (budgetError) {
          this.setState({
            checkResult: res.data.checkResultList,
            showChecking: false,
            checkingText: "",
            showCheckResult: true,
            submitting: false,
          });
        } else {
          this.setState({ directSubmitting: false, showChecking: false });
          message.success(messages("common.operate.success")); //操作成功
          this.goBack();
        }
      })
      .catch((err) => {
        info.ignoreBudgetWarningFlag = false;
        this.setState({
          showChecking: false,
          directSubmitting: false,
          showCheckResult: false,
          submitting: false,
        });
        handleSubmitError(err);
      });
  };

  //预算检查后取消继续提交
  afterBudgetCheckCancel = () => {
    this.setState(
      {
        showCheckResult: false,
        submitting: false,
      },
      () => {
        let isNeedRefresh = false;
        this.state.checkResult.map((item) => {
          if (
            item.externalPropertyName &&
            String(item.externalPropertyName) !== "9002"
          )
            isNeedRefresh = true;
        });
        if (isNeedRefresh) {
          this.getInfo(true);
          this.getExpenseList();
          this.isOverBill();
        }
      }
    );
  };

  goBack = () => {
    menuRoute.goBack(this)
  };

  handleCloseNewCreate = (refresh) => {
    this.setState({ nowEditExpense: null, showNewExpense: false });
    const { audit, approve, auditCapability } = this.state;
    //审核详情页及带有读图审核的审批详情页关闭费用详情侧滑框时重新获取费用详情（因为此时图片审核状态可能已更改）
    let fileAuditEnable = audit || (approve && auditCapability);
    // TES-1926 要求费用保存后刷新报销单数据
    this.getInfo(true);
    this.getExpenseList();
    this.isOverBill();
    // refresh && this.getInfo(true);
    // (refresh || fileAuditEnable) && this.getExpenseList();
  };

  handleAfterClose = (refresh) => {
    if (refresh) {
      this.getInfo(true);
      this.getExpenseList();
      this.auditRef && this.auditRef.refreshList();
    }
  };

  //删除费用（退回账本）
  handleDeleteExpense = (isSubsidy) => {
    this.getInfo(true);
    this.getExpenseList();
    // 若删除的是差补费用，则需要重新获取差补统计
    isSubsidy && this.getTravelSubsidy();
  };

  handlePrint = () => {
    const { info } = this.state;
    this.setState({ printLoading: true });
    baseService.printExpense(info.expenseReportOID).then((res) => {
      this.setState({ printLoading: false });
      window.open(res.data.fileURL, "_blank");
    });
  };

  onSelectExpense = (selectedRowKeys) => {
    let { expenseRowSelection, readOnly, selectInvoiceOIDs } = this.state;
    expenseRowSelection.selectedRowKeys = selectedRowKeys;
    if (!readOnly) {
      selectInvoiceOIDs = selectedRowKeys;
    }
    this.setState({ expenseRowSelection, selectInvoiceOIDs });
  };

  //外部费用导入modal控制
  openExternalExpenseImport = (flag) => {
    this.setState({ showExternalExpenseImportModal: flag });
  };

  //导入外部费用事件
  importExternalExpense = () => {
    this.openExternalExpenseImport(false);
    renderModalInfo("externalExpenseImport");
  };

  //处理审核条件
  filterAutoAuditInvoice = (invoices) => {
    const { auditTabsValue, audit } = this.state;
    if (!audit) {
      return invoices;
    }
    let invoiceArray = [];
    invoices &&
      invoices.map((item) => {
        if (auditTabsValue === "waitAudit" && !item.autoAudit) {
          invoiceArray.push(item);
        }
        if (auditTabsValue === "autoAudit" && item.autoAudit) {
          invoiceArray.push(item);
        }
      });
    return invoiceArray;
  };

  //处理筛选差补费用类型条件
  filterTravelSubsidyInvoice(invoices) {
    let { travelSubsidyType } = this.state;
    let invoiceArray = [];
    if (!travelSubsidyType) {
      return invoices;
    }
    invoices &&
      invoices.map((item) => {
        if (
          travelSubsidyType === "travel" &&
          item.expenseTypeSubsidyType === 1
        ) {
          invoiceArray.push(item);
        }
        if (
          travelSubsidyType === "normal" &&
          item.expenseTypeSubsidyType !== 1
        ) {
          invoiceArray.push(item);
        }
      });
    return invoiceArray;
  }

  //选择费用大类
  handleSelectCategory = (category, index) => {
    let { expenseRowSelection, expenseReportInvoices } = this.state;
    expenseRowSelection.selectedRowKeys = [];
    if (category === "all") {
      let showExpenseReportInvoices = filterExpenseList(expenseReportInvoices);
      this.setState({
        showExpenseReportInvoices: this.filterAutoAuditInvoice(
          showExpenseReportInvoices
        ),
        showExpenseReportInvoicesIncludeAllTab: deepFullCopy(
          expenseReportInvoices
        ),
        selectInvoiceOIDs: [],
        expenseRowSelection,
        travelSubsidyType: null,
        travelSubsidyUser: "all",
        expenseTypePieChosenIndex: "all",
      });
    } else {
      let showExpenseReportInvoices = [];
      let showExpenseReportInvoicesIncludeAllTab = [];
      category.invoices.map((invoice) => {
        invoice.invoiceView.status = invoice.status;
        invoice.invoiceView.rejectReason = invoice.rejectReason;
        showExpenseReportInvoices.push(invoice.invoiceView);
        showExpenseReportInvoicesIncludeAllTab.push(invoice.invoiceView);
      });
      showExpenseReportInvoices = this.filterAutoAuditInvoice(
        showExpenseReportInvoices
      );
      this.setState({
        showExpenseReportInvoices,
        showExpenseReportInvoicesIncludeAllTab,
        expenseRowSelection,
        selectInvoiceOIDs: [],
        expenseTypePieChosenIndex: index,
      });
    }
  };

  //选择差补类型／普通类型
  handleChangeTravelSubsidyType = (e) => {
    let travelSubsidyType = e.target.value;
    let { expenseRowSelection, expenseReportInvoices } = this.state;
    expenseReportInvoices = filterExpenseList(expenseReportInvoices);
    expenseRowSelection.selectedRowKeys = [];
    let showExpenseReportInvoices = [];
    expenseReportInvoices.map((invoice) => {
      travelSubsidyType === "travel" &&
        invoice.expenseTypeSubsidyType === 1 &&
        showExpenseReportInvoices.push(invoice);
      travelSubsidyType === "normal" &&
        invoice.expenseTypeSubsidyType !== 1 &&
        showExpenseReportInvoices.push(invoice);
    });
    let showExpenseReportInvoicesIncludeAllTab = deepFullCopy(
      showExpenseReportInvoices
    );
    showExpenseReportInvoices = this.filterAutoAuditInvoice(
      showExpenseReportInvoices
    );
    this.setState({
      showExpenseReportInvoices,
      showExpenseReportInvoicesIncludeAllTab,
      expenseRowSelection,
      travelSubsidyType,
      selectInvoiceOIDs: [],
    });
  };

  handleChangeTravelSubsidyUser = (e) => {
    let travelSubsidyUser = e.target.value;
    let { expenseRowSelection, expenseReportInvoices } = this.state;
    expenseReportInvoices = filterExpenseList(expenseReportInvoices);
    expenseRowSelection.selectedRowKeys = [];
    let showExpenseReportInvoices = [];
    if (travelSubsidyUser !== "all") {
      expenseReportInvoices.map((invoice) => {
        invoice.userOID === travelSubsidyUser &&
          showExpenseReportInvoices.push(invoice);
      });
    } else {
      showExpenseReportInvoices = expenseReportInvoices;
    }
    let showExpenseReportInvoicesIncludeAllTab = deepFullCopy(
      showExpenseReportInvoices
    );
    showExpenseReportInvoicesIncludeAllTab = this.filterTravelSubsidyInvoice(
      showExpenseReportInvoicesIncludeAllTab
    );
    showExpenseReportInvoices = this.filterAutoAuditInvoice(
      showExpenseReportInvoices
    );
    showExpenseReportInvoices = this.filterTravelSubsidyInvoice(
      showExpenseReportInvoices
    );
    this.setState({
      showExpenseReportInvoices,
      showExpenseReportInvoicesIncludeAllTab,
      expenseRowSelection,
      travelSubsidyUser,
    });
  };

  //点击确认付款
  handleConfirmPay = () => {
    this.setState({ submitting: true }, () => {
      let { info, lineIds } = this.state;
      let params = {
        comment: null,
        submittedDateEnd: null,
        currentPageIds: lineIds,
        entityType: 1002,
        excludeIds: [],
        formOids: [],
        modelEnum: "CURRENT_PAGE",
        submittedDateStart: null,
        businessCode: info.businessCode,
        applicantOid: info.applicantOID,
      };
      confirmPaymentService
        .confirmPayment("processing", params)
        .then(() => {
          this.setState({ submitting: false });
          notification.open({
            message: messages("expense-parent-report.key23" /*确认付款成功*/),
            // description: `您有1笔单据确认付款成功:)`,
            description: messages(
              "expense-parent-report.key95",
              { arg1: 1 } /*{arg1}笔单据确认付款成功*/
            ),
            icon: <Icon type="smile-circle" className="default-color-font" />,
          });
          this.goBack();
        })
        .catch((e) => {
          this.setState({ submitting: false });
          notification.open({
            message: messages("expense-parent-report.key24" /*确认付款失败*/),
            description: messages("common.error" /*可能是服务器出了点问题:(*/),
            icon: <Icon type="frown-circle" style={{ color: "#e93652" }} />,
          });
        });
    });
  };

  /*自动审核和待审核费用Tab切换*/
  auditTabsChange = (key) => {
    let { showExpenseReportInvoicesIncludeAllTab } = this.state;
    this.setState(
      {
        auditTabsValue: key,
      },
      () => {
        let showExpenseReportInvoices = this.filterAutoAuditInvoice(
          filterExpenseList(showExpenseReportInvoicesIncludeAllTab)
        );
        this.setState({ showExpenseReportInvoices });
      }
    );
  };

  //获取报销单查看来源
  getExpenseReportFrom = () => {
    const { pageFrom } = this.props.params;
    if (pageFrom === "my") {
      return "myView";
    }
    if (~this.props.location.pathname.indexOf("financial-management")) {
      //单据审核、报销单查看
      return "auditView";
    }
    return "approveView";
  };

  //切换费用组件
  switchingInvoice = (index) => {
    let { showExpenseReportInvoices } = this.state;
    this.setState({
      nowEditExpense: showExpenseReportInvoices[index],
    });
  };

  /*删除整个报销单差补费用*/
  deleteTravelSubsidyExpenseReport = () => {
    const { info, travelSubsidyUser } = this.state;
    this.setState({ confirmLoading: true });
    expenseReportService
      .deleteTravelSubsidyExpenseReport(
        info.expenseReportOID,
        travelSubsidyUser
      )
      .then((res) => {
        message.success(
          messages("common.delete.success", { name: "" }) /*删除成功*/
        );
        this.setState({ confirmLoading: false, travelSubsidyUser: "all" });
        this.getInfo(true);
        this.getExpenseList();
      })
      .catch((e) => {
        this.setState({ confirmLoading: false });
        errorMessage(e.response);
      });
  };

  /*费用列表改变*/
  invoiceColumnOnChange = (pagination, filters, sorter) => {
    let {
      showExpenseReportInvoices,
      showExpenseReportInvoicesSorterBefore,
    } = this.state;
    if (!showExpenseReportInvoicesSorterBefore) {
      showExpenseReportInvoicesSorterBefore = deepFullCopy(
        showExpenseReportInvoices
      );
    }
    let compare = function (prop, type) {
      return function (obj1, obj2) {
        if (prop === "expenseTypeName") {
          let b = obj2[prop];
          let a = obj1[prop];
          let temp = a.localeCompare(b, "zh-Hans-CN", {
            sensitivity: "accent",
          });
          if (temp === -1) {
            return type === "descend" ? 1 : -1;
          } else if (temp === 1) {
            return type === "descend" ? -1 : 1;
          }
          if (type === "descend") {
            return 0;
          }
          return 0;
        }
        let val1 = obj1[prop];
        let val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
          val1 = Number(val1);
          val2 = Number(val2);
        }
        if (val1 < val2) {
          return type === "descend" ? 1 : -1;
        } else if (val1 > val2) {
          return type === "descend" ? -1 : 1;
        } else {
          return 0;
        }
      };
    };
    if (sorter && sorter.columnKey) {
      showExpenseReportInvoices.sort(compare(sorter.columnKey, sorter.order));
    } else {
      showExpenseReportInvoices = deepFullCopy(
        showExpenseReportInvoicesSorterBefore
      );
      showExpenseReportInvoicesSorterBefore = null;
    }
    this.setState({
      showExpenseReportInvoices,
      showExpenseReportInvoicesSorterBefore,
    });
  };

  //编辑费用回调
  editNowExpenseCallBack = (invoice) => {
    let { showExpenseReportInvoices, expenseReportInvoices, info } = this.state;
    return new Promise((resolve, reject) => {
      if (invoice && invoice.invoiceOID && info && info.expenseReportOID) {
        expenseReportService
          .getExpenseAccountInfo(this.getExpenseListParams())
          .then((res) => {
            let invoiceList =
              res.data && res.data.rows
                ? res.data.rows.expenseReportInvoices || []
                : [];
            let showIndex = -1;
            let changeIndex = -1;
            invoiceList &&
              invoiceList.map((item, index) => {
                if (item.invoiceOID === invoice.invoiceOID) {
                  invoice = item.invoiceView;
                }
              });
            showExpenseReportInvoices.map((item, index) => {
              if (item.invoiceOID === invoice.invoiceOID) {
                showIndex = index;
              }
            });
            expenseReportInvoices.map((item, index) => {
              if (item.invoiceOID === invoice.invoiceOID) {
                changeIndex = index;
              }
            });
            if (showIndex != -1) {
              showExpenseReportInvoices[showIndex] = invoice;
            }
            if (changeIndex != -1) {
              expenseReportInvoices[changeIndex] = invoice;
            }
            this.setState({
              showExpenseReportInvoices,
              expenseReportInvoices,
            });
            resolve(invoice);
          })
          .catch((e) => {
            resolve(invoice);
          });
      }
    });
  };

  //新建费用
  newCreateExpense = () => {
    this.setState({
      expenseSource: "expenseType",
      showNewExpense: true,
      modalVisible: false,
    });
  };

  //修改费用归属人
  changeOwner = (value) => {
    let item = value || {};
    let owner = {
      userOID: item.userOID,
      fullName: item.fullName,
      employeeId: item.employeeID,
      companyOID: item.companyOID,
      rank: item.rank,
    };
    this.setState({
      owner,
      ownerOID: item.userOID,
    });
  };

  handleTabChange = (tab) => {
    this.setState({ tabValue: tab }, () => {
      this.setState({ expenseRowIsEdit: true });
    });
    if (tab === "requestInfo" && window.ISIE9) {
      window.location.reload();
    }
  };

  //切换日历模式
  toggleCalendarMode = () => {
    this.setState({ isCalendarMode: !this.state.isCalendarMode });
  };

  handleClearFilter = (filterCondition) => {
    const { showExpenseReportInvoices, info } = this.state;
    const { ownerOID, expenseTypeOID, date } = filterCondition;
    let baseCurrencyPrecision = queryCurrencyPrecision(info.baseCurrency);
    let filterDataSum = 0;
    let data = showExpenseReportInvoices.filter((item) => {
      return (
        (!ownerOID.length || ownerOID.indexOf(item.ownerOID) > -1) &&
        (!expenseTypeOID.length ||
          expenseTypeOID.indexOf(item.expenseTypeOID) > -1) &&
        (!date.length ||
          date.indexOf(moment(item.createdDate).format("YYYY-MM-DD ddd")) > -1)
      );
    });
    data.forEach((item) => {
      filterDataSum = addCalculate(
        filterDataSum,
        item.baseAmount.toFixed(baseCurrencyPrecision)
      );
    });
    this.setState({
      filterCondition,
      filterDataSum,
      filterData: data,
      isCalendarMode: false,
    });
  };

  //点击费用行
  handleExpenseRowClick = (record) => {
    this.setState(
      {
        showNewExpense: true,
        nowEditExpense: record,
        isCopyInvoice: false,
        debounceSlideFrame: true,
      },
      () => {
        setTimeout(() => {
          this.setState({ debounceSlideFrame: false });
        }, 600);
      }
    );
  };

  //编辑报销单表单
  editExpenseFields = (value) => {
    //刷新表单详情
    if (value && value.refresh) {
      this.getInfo(true);
    }
    //刷新费用列表
    if (value && value.refreshAccount) {
      this.getExpenseList();
      this.getTravelSubsidy();
    }
  };

  getInvoiceList = (refresh) => {
    const { info } = this.context;
    this.setState({ invoiceLoading: true });
    financeAuditService
      .getExpenseReportInvoices(info.expenseReportOID)
      .then((res) => {
        res.data.financeReceipts.forEach(this.mapFinanceInvoice);
        this.setState({ invoiceList: res.data, invoiceLoading: false });
      });
    refresh && this.props.refreshInvoice();
  };

  changeShowMore = (index, status) => {
    let list = this.state.overQuotaList;
    list[index].isShowMore = !status;
    this.setState({
      overQuotaList: list
    })
  }

  render() {
    const { profile, location, loginUser } = this.props;
    const { pageFrom } = this.props.params;
    const {
      loading,
      info,
      approvalHistory,
      applicant,
      showYingfuSelectApproveModal,
      showExternalExpenseImportModal,
      jobInfo,
      showNewExpense,
      nowEditExpense,
      expenseSource,
      form,
      auditCapability,
      batchApportion,
      loanRefund,
      showExpenseReportInvoices,
      checkingText,
      showChecking,
      submitting,
      showCheckResult,
      checkResult,
      readOnly,
      approve,
      audit,
      view,
      printLoading,
      businessCardEnabled,
      invoiceEnabled,
      ocrEnabled,
      expenseRowSelection,
      directSubmitting,
      isWithTime,
      travelSubsidy,
      travelSubsidyType,
      travelSubsidyUser,
      pay,
      subsidyFrame,
      isWithSubsidies,
      costCenterItemsApportion,
      showExpensePrew,
      showWriteOffPrew,
      failedInvoices,
      haveAutoAudit,
      tabValue,
      confirmLoading,
      isAuditInApproveStatus,
      showAssociatedBag,
      associatedData,
      expenseRowIsEdit,
      modalVisible,
      ownerOID,
      owner,
      expenseReportInvoices,
      receiptOperateScene,
      isCopyInvoice,
      showApproveBottom,
      isCalendarMode,
      filterCondition,
      filterData,
      debounceSlideFrame,
      filterDataSum,
      accountListLoading,
      invoiceGroups,
      approvalChains,
      budgetExplainNumber,
      expenseTypePieChosenIndex,
      isOverBill,
      overAppData,
      unifiedTableList,
    } = this.state;
    let hasChildren = info.children && info.children.length > 0; //有子单
    let custFormValues = info.custFormValues || []; //自定义表单
    custFormValues.map((item) => {
      if (item.messageKey === "attachment" || item.messageKey === "image") {
        item.showFileName = true; // 报销单头部附件展示名字 不展示图片
        item.attachmentImages.map((img) => {
          img.fileName = img.fileName.replace(/(.*)_(\d*)(\.)/, "$1$3");
        });
      }
    });
    let expenseReportStatus = getReportStatus(info);
    let adminApprove =
      location.pathname.indexOf("admin-approve-expense-detail") > -1; //是否是管理员审批
    let buttonRoleSwitch =
      this.checkPageRole("EXPENSEAUDIT", 2) &&
      this.checkFunctionProfiles(["er.disabled"], [[false, undefined]]) &&
      this.checkFunctionProfiles(
        ["finance.audit.disabled"],
        [[false, undefined]]
      );
    let thirdUser = undefined;
    if (info && info.formCode === 'BX006') {
      info.custFormValues.map(item => {
        if (item.fieldName === '费用确认人') {
          thirdUser= item.showValue
        }
      })
    }
    // console.log('info', expenseReportInvoices)
    let invoiceArea = (
      <div>
        {!loading && !readOnly && (
          <div className="expense-import-area">
            <If value={!profile["account.book.upsert.disabled"]}>
              <ButtonExportAccount
                extraParams={{ isOfficialCard: form.isOfficialCard }}
                info={info || {}}
                form={form || {}}
                expenseReportInvoices={expenseReportInvoices}
                onSuccess={() => {
                  this.getInfo(true);
                  this.getExpenseList();
                }}
              />
            </If>
            <Button
              onClick={() =>
                this.setState(
                  { ownerOID: "", owner: {}, receiptOperateScene: 2 },
                  () => this.newCreateExpense()
                )
              }
            >
              {messages("expense-parent-report.key36" /*新建费用*/)}
            </Button>
            <If
              value={
                form.customFormPropertyMap &&
                form.customFormPropertyMap[
                  "report.property.create.others.expense"
                ] === "true"
              }
            >
              <Button
                onClick={() =>
                  this.setState({
                    modalVisible: true,
                    ownerOID: "",
                    receiptOperateScene: 2,
                  })
                }
              >
                {messages("expense-parent-report.key109") /*新建他人费用*/}
              </Button>
            </If>
            <If value={!window.ISIE9 && profile["expenseBatchImport.isOpen"]}>
              <Button onClick={() => this.openExternalExpenseImport(true)}>
                {messages("expense-parent-report.key37" /*外部费用导入*/)}
              </Button>
            </If>
            {/* 2020-12-11 报销单-导入商务卡费用功能去掉 */}
            {/* <If value={businessCardEnabled}>
              <Button onClick={() => this.setState({expenseSource: 'businessCard', showNewExpense: true})}>
                {messages('expense-parent-report.key38' 导入商务卡费用 )}
              </Button>
            </If> */}
            <If value={invoiceEnabled}>
              <Button
                onClick={() =>
                  this.setState({
                    expenseSource: "invoice",
                    showNewExpense: true,
                    receiptOperateScene: 1,
                  })
                }
              >
                {messages("expense-parent-report.key39" /*发票查验*/)}
              </Button>
            </If>
            <If value={isWithSubsidies}>
              <Button
                onClick={() => {
                  this.setState({ subsidyFrame: true });
                }}
              >
                {messages("expense-parent-report.key40" /*补贴计算*/)}
              </Button>
            </If>
            {/*批量分摊*/}
            {/* <ButtonBatchApportion
              batchApportion={batchApportion}
              invoiceList={expenseReportInvoices}
              rowSelection={expenseRowSelection}
              expenseReport={info}
              costCenterItemsApportion={costCenterItemsApportion}
              expenseRowSelect={(value) =>
                this.setState({ expenseRowSelection: value })
              }
            /> */}
          </div>
        )}
        {!hasChildren && !isCalendarMode && (
          <ExpenseTypePie
            chosenIndex={expenseTypePieChosenIndex}
            invoiceGroups={invoiceGroups}
            handleClick={this.handleSelectCategory}
          />
        )}
        {travelSubsidy && (
          <div className="expense-report-travel-subsidy">
            <RadioGroup
              value={travelSubsidyType}
              onChange={this.handleChangeTravelSubsidyType}
            >
              <Radio value="normal">
                {messages("expense-parent-report.key42" /*普通类型*/)}
              </Radio>
              <Radio value="travel">
                {messages("expense-parent-report.key43" /*差补类型*/)}
              </Radio>
            </RadioGroup>
            <br />
            {messages("expense-parent-report.key44" /*补贴城市*/)}:&nbsp;&nbsp;
            {travelSubsidy.areas.length > 0 ? (
              travelSubsidy.areas.join(",")
            ) : (
              <span style={{ color: "#d9d9d9" }}>
                {messages("expense-parent-report.key151") /*通用城市*/}
              </span>
            )}
            <br />
            {messages("expense-parent-report.key45" /*补贴人员*/)}: &nbsp;&nbsp;
            <RadioGroup
              value={travelSubsidyUser}
              onChange={this.handleChangeTravelSubsidyUser}
            >
              <Radio value="all">{messages("common.all") /*全部*/}</Radio>
              {travelSubsidy.users.map((user) => (
                <Radio value={user.userOID} key={user.userOID}>
                  {user.fullName}
                </Radio>
              ))}
            </RadioGroup>
            <br />
            {travelSubsidyType === "travel" && !readOnly && (
              <Popconfirm
                onConfirm={this.deleteTravelSubsidyExpenseReport}
                title={messages("common.confirm.delete") /*确定要删除吗？*/}
              >
                <Button
                  loading={confirmLoading}
                  className="delete-btn"
                  style={{ marginTop: 5 }}
                >
                  {messages("common.delete.all") /*删除全部*/}
                </Button>
              </Popconfirm>
            )}
          </div>
        )}
        <If value={audit && haveAutoAudit}>
          <Tabs type="card" onChange={this.auditTabsChange}>
            {auditTabs.map((pane) => (
              <TabPane tab={pane.title} key={pane.key} />
            ))}
          </Tabs>
        </If>
        <Condition>
          <If value={isCalendarMode}>
            <ExpenseCalendarTable
              dataSource={showExpenseReportInvoices}
              applicant={info.applicantOID}
              toggleMode={this.toggleCalendarMode}
              filterData={this.handleClearFilter}
              baseCurrency={info.baseCurrency}
            />
          </If>
          <Else>
            <ExpenseAccountTable
              reportInvoiceApprovalReqDTOList={
                this.state.reportInvoiceApprovalReqDTOList
              }
              loading={accountListLoading}
              readOnly={readOnly}
              auditable={
                this.getExpenseReportFrom() === "auditView" &&
                this.props.params.tab === "prending_audit"
              }
              pageFrom={this.getExpenseReportFrom()}
              filterData={filterData}
              showExpenseReportInvoices={showExpenseReportInvoices}
              filterCondition={filterCondition}
              expenseRowSelection={expenseRowSelection}
              filterDataSum={filterDataSum}
              expenseReportStatus={expenseReportStatus}
              info={info}
              approvalChains={approvalChains}
              form={form}
              batchApportion={batchApportion}
              handleView={(record) =>
                this.setState({ showNewExpense: true, nowEditExpense: record })
              }
              handleEdit={(record) =>
                this.setState({
                  readOnly: false,
                  showNewExpense: true,
                  isCopyInvoice: false,
                  nowEditExpense: record,
                })
              }
              handleCopy={(record) =>
                this.setState({
                  showNewExpense: true,
                  nowEditExpense: record,
                  isCopyInvoice: true,
                })
              }
              handleDelete={this.handleDeleteExpense}
              handleChangeInvoiceColumns={this.invoiceColumnOnChange}
              toggleCalendarMode={this.toggleCalendarMode}
              handleClearFilter={this.handleClearFilter}
              handleRowClick={this.handleExpenseRowClick}
              onAuditChange={this.handleAuditChange}
              thirdUser={thirdUser}
            />
            {isOverBill === true && info.status !== 1001 && (
              <p style={{ fontsize: "22px", paddingTop: "15px" }}>
                {messages("expense-over-bill.key001") /*超申请信息*/}
              </p>
            )}
            {isOverBill === true && info.status !== 1001 && (
              <Table
                columns={overAppcolumns}
                dataSource={overAppData}
                pagination={false}
                bordered
              />
            )}
          </Else>
        </Condition>
      </div>
    );
    let showInvoiceTab = audit && ocrEnabled;
    let showCertificate = showExpensePrew || showWriteOffPrew;
    let tabVisible = showInvoiceTab || showCertificate;
    // console.log('expenseReportInvoices============', expenseReportInvoices)
    let expenseReportInvoicesContent = (
      <div>
        <div className="detail-tabs">
          <Condition>
            <If value={tabVisible}>
              <Tabs>
                <TabPane
                  tab={messages("expense-parent-report.key92") /*费用*/}
                  key="expense"
                >
                  {invoiceArea}
                </TabPane>
                {showInvoiceTab && (
                  <TabPane
                    tab={messages("expense-parent-report.key213") /*发票*/}
                    key="invoice"
                  >
                    {loading ? (
                      <Spin />
                    ) : (
                      <AuditApplicationInvoices
                        baseInfo={Object.assign({}, info, {
                          userOID: info.applicantOID,
                        })}
                        onRefreshInvoice={() => this.getInvoiceList(true)}
                        onRef={(inst) => (this.auditRef = inst)}
                        info={info}
                        invoiceEnabled={invoiceEnabled}
                        isAuditInApproveStatus={isAuditInApproveStatus}
                      />
                    )}
                  </TabPane>
                )}
                {showCertificate && (
                  <TabPane
                    tab={messages("expense-parent-report.key243") /*凭证预览*/}
                    key="preview"
                  >
                    <CertificatePreview
                      showExpensePrew={showExpensePrew}
                      showWriteOffPrew={showWriteOffPrew}
                      bookDate={info.bookDate}
                      params={{
                        businessCode: info.businessCode,
                        entityType: 1002,
                        setOfBooksId: info.setOfBooksId,
                        operatorOid: loginUser.userOID,
                        forceRefresh: false,
                      }}
                    />
                  </TabPane>
                )}
              </Tabs>
            </If>
            <Else>{invoiceArea}</Else>
          </Condition>
        </div>
        {(this.state.hasPayInfo && this.state.hasPayInfo.length) ||
        info.status === 1001 && info.formCode !== 'BX006' ? (
          <div className="detail-tabs">
            <PayInfo
              expenseReportOID={this.props.params.expenseReportOID}
              userOid={applicant.userOID}
              selectInvoiceOIDs={expenseRowSelection.selectedRowKeys}
              expenseReportInvoices={expenseReportInvoices}
              clearSelectInvoiceOIDs={() => {
                let { expenseRowSelection } = this.state;
                expenseRowSelection.selectedRowKeys = [];
                this.setState({ expenseRowSelection });
              }}
              formInfo={form}
              handleLineId={(res, repaymentDTOList, writeOffLoanList) => {
                console.log("repaymentDTOList", repaymentDTOList);
                this.setState({ lineIds: res, hasPayInfo: repaymentDTOList, writeOffLoanList: writeOffLoanList });
              }}
              operateMode={!loading && !readOnly ? "edit" : "readOnly"}
              expenseRowIsEdit={expenseRowIsEdit}
              expenseInfo={info}
              afterReload={() => this.setState({ expenseRowIsEdit: false })}
              afterWriteOff={() => this.getInfo(true)}
              pageFrom={this.getExpenseReportFrom()}
            />
          </div>
        ) : (
          ""
        )}
      </div>
    );
    //强管控时不允许提交报销单
    let budgetError = false;
    checkResult.map((item) => {
      budgetError = budgetError || item.type === 1;
    });
    info.admin = adminApprove;
    let warningList = [
      { title: messages("expense-over-bill.key002") /*费用超申请*/, type: 0 },
    ];
    let conditions =
      filterCondition.ownerOID.length +
      filterCondition.expenseTypeOID.length +
      filterCondition.date.length;
    let auditRejectList = conditions ? filterData : showExpenseReportInvoices;
    let auditRejectBaseList = [];
    auditRejectList.map(item => {
      auditRejectBaseList.push({
        approvalStatus: 1001,
        expenseReportOID: this.props.params.expenseReportOID,
        // expenseReportInvoiceOID,
        invoiceOID: item.invoiceOID,
        expenseTypeName: item.expenseTypeName,
        amount: item.amount,
        createdDate: item.createdDate,
        ['approvalStatus']: 1001,
      })
    })
    // console.log('filterData', auditRejectBaseList)
    return (
      <div
        className={`base-expense-report-detail background-transparent ${
          showNewExpense ? "container-hidden" : ""
        }`}
      >
        <div className="tabs-info">
          <Tabs onChange={this.handleTabChange} type="card">
            <TabPane
              tab={messages("expense-parent-report.key1" /*报销单信息*/)}
              key="requestInfo"
            >
              {/* {isOverBill === true && (
                <ExpenseDetailAlert noPrint={false} warningList={warningList} />
              )} */}
              {info.status && (info.status === 1002 ? (approvalChains && approvalChains[0]) : true) && (
                <ExpenseDetailStep
                  info={info}
                  approvalChains={approvalChains}
                  type="expense"
                />
              )}
              <ExpenseDetailHeader
                loading={loading}
                info={info}
                jobInfo={jobInfo}
                applicant={applicant}
                approvalChains={approvalChains}
                showExpenseReportInvoices={showExpenseReportInvoices}
                pageFrom={this.getExpenseReportFrom()}
                showEditBookDate={
                  this.getExpenseReportFrom() === "auditView" &&
                  this.props.params.tab === "prending_audit"
                }
                afterSaveBookDate={(value) =>
                  this.setState({
                    info: Object.assign(info, { bookDate: value }),
                  })
                }
              />
            </TabPane>
            {budgetExplainNumber > 0 && false && (
              <TabPane
                tab={messages("expense-parent-report.key208") /*预算执行信息*/}
                key="budgetExplain"
              >
                <BudgetExplain documentType="EXP_REPORT" documentId={info.id} />
              </TabPane>
            )}
            {approvalHistory && !!approvalHistory.length && (
              <TabPane
                tab={messages("expense-parent-report.key2" /*审批进度*/)}
                key="approvals"
              >
                <ApproveHistory
                  businessCode={info.businessCode}
                  isShowReply={pageFrom === "my" && info.status === 1003}
                  approvalChains={approvalChains}
                  approvalHistory={approvalHistory}
                  applicantInfo={applicant}
                  type="expense"
                />
              </TabPane>
            )}
          </Tabs>
          {/*多级审核审核并发标记 || 审批流审批并发标记*/}
          <ConcurrentMark
            entityOID={this.props.params.expenseReportOID}
            approvalChains={approvalChains}
            isAuditInApproveStatus={isAuditInApproveStatus}
          />
        </div>
        <If value={tabValue === "requestInfo"}>
          <div style={{ margin: "0 -20px", overflowX: "hidden" }}>
            <div className="detail-tabs detail-tabs-content">
              <ExpenseReportFields
                loading={loading}
                readOnly={readOnly}
                propsObj={this.props}
                info={info}
                jobInfo={jobInfo}
                applicant={applicant}
                custFormValues={custFormValues}
                pageFrom={this.getExpenseReportFrom()}
                form={form}
                expenseReportInvoices={expenseReportInvoices}
                afterSaveByApprover={() => this.getInfo(true)}
                afterSaveByMyself={this.editExpenseFields}
              />
            </div>
            {unifiedTableList.map((tableData) => {
              return (
                <div
                  key={tableData.fieldName}
                  className="detail-tabs detail-tabs-content"
                  style={{ marginBottom: "15px" }}
                >
                  <div className="request-info">
                    <div className="tab-container">
                      <h3 className="sub-header-title">
                        {tableData.fieldName}
                      </h3>
                    </div>
                    <div>
                      {/* <pre>{JSON.stringify(tableData, null, 2)}</pre> */}
                      <UnifiedTable
                        key={tableData.value}
                        showIndex
                        readonly
                        exportFile={false}
                        importFile={false}
                        cellMinWidth={100}
                        formField={tableData.formField}
                        value={tableData.value}
                      />
                    </div>
                  </div>
                </div>
              );
            })}
            <div>{expenseReportInvoicesContent}</div>
          </div>
        </If>
        <div style={{ marginTop: 60 }} />
        {/*fix bug 27578*/}
        <If value={approve || adminApprove}>
          <ApproveExpenseReportDetail
            info={info}
            isAuditInApproveStatus={isAuditInApproveStatus}
            showApproveBottom={showApproveBottom || adminApprove}
            selectedExpense={expenseRowSelection.selectedRowKeys}
            customFormPropertyMap={form.customFormPropertyMap}
            expenseReportInvoices={expenseReportInvoices}
            approvalChains={approvalChains}
            approvalHistory={approvalHistory}
            afterClose={this.handleAfterClose}
            invoiceEnabled={invoiceEnabled}
            failedInvoices={failedInvoices}
          />
        </If>
        {audit &&
          (buttonRoleSwitch ? (
            <AuditApplicationDetail
              reportInvoiceApprovalReqDTOList={
                this.state.reportInvoiceApprovalReqDTOList
              }
              formOID={info.formOID}
              entityOID={info.expenseReportOID}
              status={info.status}
              isAuditInApproveStatus={isAuditInApproveStatus}
              companyOid={info.docCompanyOID}
              applicantOID={info.applicantOID}
              entityType={1002}
              tab={this.props.params.tab}
              businessCode={info.businessCode}
              parentBusinessCode={info.parentBusinessCode}
              afterClose={this.handleAfterClose}
              invoiceEnabled={invoiceEnabled}
              approvalHistory={approvalHistory}
              failedInvoices={failedInvoices}
              customFormPropertyMap={form.customFormPropertyMap}
              info={info}
              approvalChains={approvalChains}
            />
          ) : (
            <Affix offsetBottom={0} className="bottom-bar">
              <Button
                onClick={this.handlePrint}
                type="primary"
                className="back-btn"
                loading={printLoading}
              >
                {messages("common.print") /*打印*/}
              </Button>
              <Button className="back-btn" onClick={this.goBack}>
                {messages("common.back") /*返回*/}
              </Button>
            </Affix>
          ))}
        {!audit && !approve && view && (
          <Affix offsetBottom={0} className="bottom-bar">
            <Button
              onClick={this.handlePrint}
              type="primary"
              className="back-btn"
              loading={printLoading}
            >
              {messages("common.print") /*打印*/}
            </Button>
            <ButtonPrintCertificate
              businessCode={info.businessCode}
              parentBusinessCode={info.parentBusinessCode}
              appCode={"Exp_Report_Print_Doc"}
            />
          </Affix>
        )}
        {pay && (
          <Affix offsetBottom={0} className="bottom-bar">
            {info.status === 1008 &&
              expenseReportStatus.state === "processing" &&
              this.checkPageRole("EXPENSEPAYMENT", 2) && (
                <Button
                  type="primary"
                  className="back-btn"
                  onClick={this.handleConfirmPay}
                  loading={submitting}
                >
                  {messages("expense-parent-report.key46" /*确认已付款*/)}
                </Button>
              )}
            <Button className="back-btn" onClick={this.goBack}>
              {messages("common.back") /*返回*/}
            </Button>
          </Affix>
        )}
        <If
          value={
            !audit && !approve && !view && !pay && !loanRefund && !adminApprove
          }
        >
          <ButtonsBarBottom
            form={form}
            info={info}
            approvalChains={approvalChains}
            expenseReportInvoices={expenseReportInvoices}
            submitting={submitting}
            onSubmit={this.handleSubmit}
          />
        </If>

        {!loading && !accountListLoading && (
          <SlideFrame
            show={showNewExpense}
            content={NewExpense}
            title={
              readOnly
                ? messages("expense-parent-report.key47" /*查看费用*/)
                : nowEditExpense && !isCopyInvoice
                ? messages("expense-parent-report.key48" /*编辑费用*/)
                : messages("expense-parent-report.key36" /*新建费用*/)
            }
            params={{
              type: 3,
              isCopy: isCopyInvoice,
              nowExpense: nowEditExpense,
              expenseReport: info,
              expenseSource,
              showExpenseReportInvoices,
              readOnly,
              approve,
              isWaitForAudit: info.status === 1003 || isAuditInApproveStatus,
              audit,
              view,
              pay,
              auditCapability,
              slideFrameShowFlag: showNewExpense,
              businessCardEnabled,
              costCenterItemsApportion,
              applicant: applicant,
              switchingInvoice: this.switchingInvoice,
              editNowExpenseCallBack: this.editNowExpenseCallBack,
              hasInit: false,
              owner,
              receiptOperateScene,
              isWithTime,
              tab: this.props.params.tab,
              pageFrom: this.getExpenseReportFrom(),
              expenseReportInvoices,
              jobInfo,
              onClose:this.handleCloseNewCreate,
            }}
            onClose={() =>
              !debounceSlideFrame &&
              this.setState({ showNewExpense: false, nowEditExpense: null })
            }
            afterClose={this.handleCloseNewCreate}
            hasFooter={false}
            width="800px"
          />
        )}

        <Modal
          visible={showChecking}
          maskClosable={false}
          footer={null}
          closable={false}
          wrapClassName="expense-report-checking"
        >
          <img src={loadingImg} className="checking-img" />
          <img src={auditingImg} className="checking-img-content" />
          <div className="checking-divide" />
          <div className="checking-title">{checkingText}</div>
          <div className="checking-content">
            {messages("common.waiting") /*请稍等...*/}
          </div>
        </Modal>

        {/*报销单提交时检查结果*/}
        <ExpenseCheckResult
          visible={showCheckResult}
          checkResult={checkResult}
          submitLoading={directSubmitting}
          confirmSubmit={this.confirmSubmit}
          onCancel={this.afterBudgetCheckCancel}
          overAppcolumns={overAppcolumns}
          overAppData={overAppData}
        />

        <ExpenseAssociatedBag
          visible={showAssociatedBag}
          dataObj={associatedData}
          expenseReportId={info.id}
          onCancel={() =>
            this.setState({ showAssociatedBag: false, submitting: false })
          }
          onSuccess={() =>
            this.setState(
              { showAssociatedBag: false },
              this.handleCheckTravelStandard
            )
          }
        />

        {/*外部费用导入视图*/}
        <ExternalExpenseImport
          visible={showExternalExpenseImportModal}
          title={messages("expense-parent-report.key37" /*外部费用导入*/)}
          expenseReportOID={info.expenseReportOID}
          formOID={info.formOID}
          userOID={info.applicantOID}
          applicationOID={info.applicationOID}
          createTableShow={false}
          onOk={this.importExternalExpense}
          afterClose={() => this.openExternalExpenseImport(false)}
        />
        {info.expenseReportOID && showYingfuSelectApproveModal && (
          <YingfuSelectApprove
            visible={showYingfuSelectApproveModal}
            expenseReport={info}
            onOk={this.submitYingfuApprove}
            afterClose={() => this.openYingfuSelectApprove(false)}
          />
        )}

        <SubsidySlideFrame
          visible={subsidyFrame}
          expenseInfo={info || {}}
          afterClose={(isRefresh) => {
            this.setState({ subsidyFrame: false });
            if (isRefresh === true) {
              this.getInfo();
              this.getExpenseList();
            }
          }}
        />
        <Modal
          visible={modalVisible}
          title={messages("expense-parent-report.key109") /*新建他人费用*/}
          onOk={ownerOID ? this.newCreateExpense : () => {}}
          onCancel={() => this.setState({ modalVisible: false })}
        >
          <Row style={{ marginTop: 20 }}>
            <Col
              span={6}
              style={{
                textAlign: "right",
                paddingRight: 10,
                lineHeight: "32px",
              }}
            >
              {messages("expense-parent-report.key105") /*费用归属人*/}：
            </Col>
            <Col span={14}>
              <Selector
                type="expenseOwner"
                entity
                params={{ expenseReportOID: info.expenseReportOID }}
                value={ownerOID}
                onChange={this.changeOwner}
              />
            </Col>
          </Row>
        </Modal>
        <Modal
          title="按照政策规定，您的报销存在以下超额，请修改后重新提交"
          closable={false}
          footer={<Button type="primary" onClick={() => this.setState({ overQuotaVisible: false })}>确定</Button>}
          visible={this.state.overQuotaVisible}
          width={600}
        >
          <div className="over-quota-modal-box">
            {this.state.overQuotaList && this.state.overQuotaList.map((item, index) => (
              <div className="over-quota-modal-box-tap" key={index}>
                <div className="title-box">
                  <div className="title">{index+1}、{item.title}</div>
                  {item.subs && item.subs.length > 0 && <div>
                    {item.isShowMore ? <Icon type="up-circle" style={{ color: '#1890ff' }} onClick={()=>this.changeShowMore(index, item.isShowMore)} /> : <Icon type="down-circle" style={{ color: '#1890ff' }} onClick={()=>this.changeShowMore(index, item.isShowMore)} />}
                  </div>}
                </div>
                <div className="over-quota-table">
                  {item.subs && item.isShowMore && (<Table
                    columns={overQuotacolumns}
                    dataSource={item.subs}
                    pagination={false}
                    scroll={{ x: 750 }}
                    bordered
                    title={() => <div className="over-quota-table-title">报销金额总计：<span>{item.subs[0].currency} {formatNumber(Number(item.totalTrueAmt).toFixed(2))}</span></div>}
                  />)}
                </div>
              </div>
            ))}
          </div>
        </Modal>
      </div>
    );
  }
}

ExpenseReportDetail.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    company: state.login.company,
    user: state.login.user,
    loginUser: state.login.loginUser,
  };
}

export default connect(mapStateToProps)(ExpenseReportDetail);
